package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author kw
 * @program demo1
 * @description
 * @create 2024 - 11 - 29 18:15
 **/
@Service
public class CommonQueryServiceImpl implements CommonQueryService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private OrderMapper orderMapper;

    @Override
    public Page<?> queryData(Map condition,String tableName) {
      //  Object tableName = condition.get("tableName");
        BaseMapper<?> mapper = null;
        if ("user".equals(tableName)) {
            mapper = userMapper;
        } else if ("product".equals(tableName)) {
            mapper = orderMapper;
        }
        if (Objects.isNull(mapper)) {
            throw new IllegalArgumentException("Invalid table name");
        }
        Integer currentPage = (Integer) condition.get("currentPage");
        Integer pageSize = (Integer) condition.get("pageSize");
        Page page = new Page<>(currentPage, pageSize);
        // 必须要移除以下参数
        condition.remove("tableName");
        condition.remove("currentPage");
        condition.remove("pageSize");
        QueryWrapper queryWrapper = new QueryWrapper<>();
        // 根据传入的条件动态构建QueryWrapper，例如如果条件中有username字段用于查询用户
        condition.forEach(queryWrapper::eq);

        return mapper.selectPage(page, queryWrapper);
    }

}
